﻿using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Ocelot.DependencyInjection;
using Ocelot.Middleware;
using Ocelot.Provider.Consul;
using Ocelot.Provider.Nacos;
using Ocelot.Provider.Polly;
using System;
using System.Threading.Tasks;
using Zhongjiu.Common;

namespace Zhongjiu.Gateway.Extensions
{
  public static class CustomOcelotSetup
  {
    public static void AddCustomOcelotSetup(this IServiceCollection services)
    {
      if (services == null) throw new ArgumentNullException(nameof(services));

      //var basePath = AppContext.BaseDirectory;

     var builder= services.AddOcelot().AddDelegatingHandler<CustomResultHandler>();
      if (Appsettings.app("Nacos:Enabled").ToBool())
      {
          builder.AddNacosDiscovery().AddPolly();
      }
      if (Appsettings.app("Consul:EnabledRegister").ToBool())
      {
        builder.AddConsul().AddPolly();
      }
    }

    public static async Task<IApplicationBuilder> UseCustomOcelotMidd(this IApplicationBuilder app)
    {
      await app.UseOcelot();
      return app;
    }

  }
}
